package tt.love.hw.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.commons.beanutils.BeanUtils;

import tt.love.hw.PMF;
import tt.love.hw.jdo.Comment;
import tt.love.hw.jdo.User;

public class CommentService {

	public void createComment(Comment comment) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(comment);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Comment> getCommentList(String appId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Comment.class);
			Map<String, String> filterMap = new HashMap<String, String>();
			query.setFilter("appId == sAppId");
			query.declareParameters("String sAppId");
			filterMap.put("sAppId", appId);
			List<Comment> resultComment = (List<Comment>) query
					.executeWithMap(filterMap);
			List<Comment> commentListWithoutObjectManager = new ArrayList<Comment>();
			for (Comment oldComment : resultComment) {
				Comment newComment = new Comment();
				BeanUtils.copyProperties(newComment, oldComment);
				newComment.setCommentUserName(pm.getObjectById(User.class,newComment.getCommentUserId()).getUserName());
				commentListWithoutObjectManager.add(newComment);
			}
			return commentListWithoutObjectManager;
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} finally {
			pm.close();
		}
	}

}
